<template>
  <CommonNav title="课程详情" />
  <CommonMain>
    <CommonLack v-show="!course" />
    <div class="mt-5" v-if="course">
      <div class="card bg-base-100 shadow-xl mb-5">
        <courseCard :course="course">
          <div class="flex items-center justify-between gap-2">
            <div class="text-xs text-gray-400">
              共{{ courseChapter.length }}个章节
            </div>
            <div class="flex gap-2">
              <button class="btn btn-active" v-if="userCourseId">已获取</button>
              <button
                class="btn btn-primary"
                v-if="!userCourseId && courseChapter.length"
                @click="clickOpenCourse(courseId)"
              >
                获取课程
              </button>
              <nuxt-link :to="`/user-course/${userCourseId}`">
                <button class="btn btn-primary" v-if="userCourseId">
                  开始学习
                </button>
              </nuxt-link>
            </div>
          </div>
        </courseCard>
      </div>
      <chapter :chapter="courseChapter" :isClick="false" />
    </div>
  </CommonMain>
</template>
<script setup lang="ts">
import { getCourseDetail } from "~/composables/course/course";
import { getCourseChapter } from "~/composables/course/chapter";
import { getUserCourseId, userOpenCourse } from "~/composables/user/course";
import { userSet } from "~/composables/common/user";
import { toast } from "vue-sonner";
import { dialogJs } from "~/composables/common/dialog";
import { celebrate } from "~/composables/common/celebrate";
const { getUserData } = userSet();
const { diaLogShow } = dialogJs();
const courseId = useRoute().params.id as string;
const userCourseId = ref();
const course = await getCourseDetail(courseId);
const courseChapter = await getCourseChapter(courseId);
const clickOpenCourse = async (courseId: string) => {
  if (!getUserData()) {
    diaLogShow({
      title: "提示",
      content: "您还没有登录，是否立即登录？",
      link: "/login",
      confirmText: "立即登录",
    });
    return;
  }
  const relust = await userOpenCourse(courseId);
  if (relust.statusCode == 200) {
    celebrate();
    toast.success(relust.message, {
      duration: 3000,
    });
    userCourseId.value = await getUserCourseId(courseId);
  }
};

onMounted(async () => {
  if (getUserData()) {
    userCourseId.value = await getUserCourseId(courseId);
  }
});
</script>

<style scoped></style>
~/composables/user/userCourse
